#ifndef CMD_H
#define CMD_H

#include <string>
#include <vector>
#include <map>

#include "../libs/libfm.h"
#include "utils.h"

using namespace std;

class CMD {

public:

    typedef void (*Command)(string path, vector<string> args);
    inline static string copiedPath;
    inline static string movedPath;

    CMD() {};

    bool launchCommand(string cmd, string path) {
        map<string, Command> commands = this->getCommands();
        vector<string> args; split(cmd, ' ', args);
        cmd = args[0]; args.erase(args.begin());

        if (commands.find(cmd) != commands.end()) {
            commands[cmd](path, args);   
            return true;
        }
        return false;
    }

    map<string, Command> getCommands() {
        return { 
            {"cp", this->cp}, 
            {"mv", this->mv},
            {"rm", this->rm},
            {"pt", this->pt},
            {"sh", this->sh}
        };
    }

    static void cp(string path, vector<string> args) {
        if (args.size() > 1)
            libfm::copy(args[0], args[1]);
        else
            CMD::copiedPath = path; 
    }
    
    static void pt(string path, vector<string> args) {
        CMD::ptCopiedPath(path, args);
        CMD::ptMovedPath(path, args);
    }

    static void mv(string path, vector<string> args) {
        if (args.size() > 1) 
            libfm::move(args[0], args[1]);
        else 
            CMD::movedPath = path;
    };
    
    static void rm(string path, vector<string> args) {
        if (args.size() > 0)
            libfm::rm(args[0]);
        else 
            libfm::rm(path);
    }

    static void sh(string path, vector<string> args) {
        if (args.size() > 0) {
            string command = "";
            for (const auto &arg : args) {
                command += arg + " ";
            }
            replace(command, "./", libfm::getDirname(path) + "/");
            system(command.c_str());
        }
    }
   

private:

    static void ptCopiedPath(string path, vector<string> args) {   
        if (CMD::copiedPath != "") {
            if (args.size() > 0) 
                libfm::copy(
                    copiedPath, 
                    libfm::getDirname(path) + "/" + args[0]
                );
            else
                libfm::copy(
                    copiedPath, 
                    libfm::getDirname(path)
                );
        }
    }

    static void ptMovedPath(string path, vector<string> args) {
        if (CMD::movedPath != "") {
            if (args.size() > 0) 
                libfm::move(
                    movedPath, 
                    libfm::getDirname(path) + "/" + args[0]
                );
            else
                libfm::move(
                    movedPath, 
                    libfm::getDirname(path) + "/" + libfm::getFilename(movedPath)
                );
        }
    }
};


#endif // CMD_H


